package com.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.entity.Order;
import com.bookstore.entity.OrderItem;
import com.bookstore.mapper.OrderItemMapper;
import com.bookstore.mapper.OrderMapper;
import com.bookstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    @Transactional
    public Integer createOrder(Integer userId, List<OrderItem> orderItems, String shippingAddress, String paymentMethod) {
        // 计算订单总金额
        BigDecimal totalAmount = orderItems.stream()
                .map(item -> item.getUnitPrice().multiply(new BigDecimal(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setTotalAmount(totalAmount);
        order.setStatus("pending");
        order.setShippingAddress(shippingAddress);
        order.setPaymentMethod(paymentMethod);
        save(order);

        // 保存订单详情
        orderItems.forEach(item -> {
            item.setOrderId(order.getOrderId());
            orderItemMapper.insert(item);
        });

        return order.getOrderId();
    }

    @Override
    public IPage<Order> getUserOrders(Integer userId, int page, int size) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getUserId, userId)
                .orderByDesc(Order::getCreatedAt);
        return page(new Page<>(page, size), queryWrapper);
    }

    @Override
    public List<OrderItem> getOrderItems(Integer orderId) {
        LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItem::getOrderId, orderId);
        return orderItemMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public boolean updateOrderStatus(Integer orderId, String status) {
        Order order = getById(orderId);
        if (order == null) {
            throw new IllegalArgumentException("订单不存在");
        }
        order.setStatus(status);
        return updateById(order);
    }

    @Override
    @Transactional
    public boolean cancelOrder(Integer orderId) {
        return updateOrderStatus(orderId, "cancelled");
    }
} 